const jsonfile = require('jsonfile');
const notifyFun={
    setNotify(info,msg,readInfo=[],origin=0){
        const msgInfo={}
        const notifyList=jsonfile.readFileSync(`data/notify.json`)
        //通知超过一定条数移除
        const notifyInfo=Object.keys(notifyList)
        if(notifyInfo.length>500){
            //移除最后一条
            const k=notifyInfo[notifyInfo.length-1]
            delete notifyList[k]
        }
        msgInfo[info]={info,msg,readInfo,origin};
        if(!global.notifyList){
            global.notifyList=notifyFun.getNotify()
        }else {
            if(global.notifyList.length>50){
                global.notifyList.pop()
            }
            global.notifyList.unshift({info,msg,readInfo,origin})
        }
        jsonfile.writeFileSync(`data/notify.json`,{...msgInfo,...notifyList})
    },
    getNotify(username=''){
        let notifyList={}
        try {
            notifyList=jsonfile.readFileSync(`data/notify.json`)
        }catch {
            jsonfile.writeFileSync(`data/notify.json`,{})
        }
        const showNotify=Object.keys(notifyList).filter(info=>!(notifyList[info].readInfo.filter(i=>!i.create_time).map(i=>i.username) || []).includes(username))
        return showNotify.map(k=>notifyList[k])
    },
    readNotify(info,username,create_time){
        const notifyList=jsonfile.readFileSync(`data/notify.json`)
        if(!notifyList[info].readInfo){
            notifyList[info].readInfo=[{username,create_time}]
        }else {
            const userIndex=notifyList[info].readInfo.findIndex(i=>i.username===username)
            notifyList[info].readInfo[userIndex].create_time=create_time
        }
        if(!notifyList[info]) return {code: 1,msg: '没有此条通知信息'}
        jsonfile.writeFileSync(`data/notify.json`,notifyList)
        if(!global.notifyList){
            global.notifyList=notifyFun.getNotify()
        }else {
            const index=global.notifyList.findIndex(i=>i.info===info)
            if(global.notifyList[index].readInfo){
                const userIndex=global.notifyList[index].readInfo.findIndex(i=>i.username===username)
                global.notifyList[index].readInfo[userIndex].create_time=create_time
            }else {
                global.notifyList[index].readInfo=[{username,create_time}]
            }
        }
    }
}
module.exports=notifyFun